import request from '../../../utils/request'
Page({
  data: {
    isEditing: false,
    auserInfo: {
      avatar: '/images/user-avatar.png',
      name: '张三',
      gender: '男',
      age: 35,
      phone: '138****1234',
      idCard: '110**********1234',
      currentAddress: '',
      registeredAddress: '',
      region: ['北京市', '北京市', '东城区'],
      nativePlace: '',
      ethnicGroup: '汉族',
      educationLevel: '本科',
      maritalStatus: '已婚',
      occupation: '',
      workplace: '',
      emergencyContact: '',
      emergencyPhone: '',
      medicalInstitution: ''
    },
    userInfo:{},
    healthInfo: {
      height: 175,
      weight: 70,
      bloodPressure: '120/80',
      bloodSugar: '5.6',
      bloodType: 'A型',
      allergyHistory: '无',
      pastMedicalHistory: '无',
      familyHistory: '无'
    },
    bloodTypes: ['A型', 'B型', 'AB型', 'O型'],
    bloodTypeIndex: 0,
    ethnicGroups: ['汉族', '蒙古族', '回族', '藏族', '维吾尔族', '苗族', '彝族', '壮族', '布依族', '朝鲜族', '满族', '侗族', '瑶族', '白族', '土家族', '哈尼族', '哈萨克族', '傣族', '黎族', '傈僳族', '佤族', '畲族', '高山族', '拉祜族', '水族', '东乡族', '纳西族', '景颇族', '柯尔克孜族', '土族', '达斡尔族', '仫佬族', '羌族', '布朗族', '撒拉族', '毛南族', '仡佬族', '锡伯族', '阿昌族', '普米族', '塔吉克族', '怒族', '乌孜别克族', '俄罗斯族', '鄂温克族', '德昂族', '保安族', '裕固族', '京族', '塔塔尔族', '独龙族', '鄂伦春族', '赫哲族', '门巴族', '珞巴族', '基诺族'],
    ethnicGroupIndex: 0,
    educationLevels: ['初中/中专', '高中', '本科', '研究生', '博士'],
    educationLevelIndex: 5,
    maritalStatuses: [ '已婚','未婚'],
    maritalStatusIndex: 1,
    allergyOptions: [
      { name: '有', value: '有' },
      { name: '无', value: '无' }
    ],
    medicalHistoryOptions: [
      { name: '有', value: '有' },
      { name: '无', value: '无' }
    ],
    familyHistoryOptions: [
      { name: '有', value: '有' },
      { name: '无', value: '无' }
    ]
  },

  onLoad: function(options) {
    
    this.getUserInfo()
    .then(userInfo=>{
        this.setData({
            userInfo:userInfo
        })
         // 从 userInfo 中获取 culture 数据并进行映射
         const culture = userInfo.culture;
         const marry = userInfo.marry;
         if (culture) {
             // 创建文化程度数字和 educationLevels 数组索引的映射对象
             const cultureIndexMap = {
                 1: 0, // 初中/中专
                 2: 1, // 高中
                 3: 2, // 本科
                 4: 3, // 研究生
                 5: 4  // 博士
             };
             const index = cultureIndexMap[culture];
             if (index!== undefined) {
                 this.setData({
                    educationLevelIndex: index
                 });
             }
         }
         if (marry) {
            const marryIndexMap = {
                1: 0, // 已婚
                2: 1, // 未婚
            };
            const index = marryIndexMap[marry];
            if (index!== undefined) {
                this.setData({
                    maritalStatusIndex: index
                });
            }
        }
    })
    //血压
    this.getBloodPressure()
    .then(bloodPressure=>{
        this.setData({
            bloodPressure:bloodPressure
        })
    })
    //体重
    this.getUserWeight()
    .then(bloodsuger=>{
        this.setData({
            bloodsuger:bloodsuger
        })
    })

    //血糖
    this.getBloodSuger()
    .then(userweight=>{
        this.setData({
            userweight:userweight
        })
    })
  },
  onEducationLevelChange: function (e) {
        const selectedIndex = e.detail.value;
        const selectedEducation = this.data.educationLevels[selectedIndex];
        this.setData({
            selectedEducationIndex: selectedIndex,
            'userInfo.culture': selectedEducation.value
        });
    },
  //获取用户详情
  getUserInfo(){
    return new Promise((resolve,reject)=>{
        let userId = wx.getStorageSync('userid')
        let url = `resident/resident/${userId}`
        request({
            url:url,
            method:'GET',
            success(res){
                let userInfo = res.data.data
                // console.log("userinfo:",userInfo);
                resolve(userInfo)
            },fail(error){
                reject(error)
            }
        })
    })
  },
  //获取用户血压
  getBloodPressure(){
    return new Promise((resolve,reject)=>{
        let userId = wx.getStorageSync('userid')
        let bloodPressureid = 3  //数据库中血压id=3
        let url = `healthlog/healthlog/selectByUseridAndTypeid?userid=${userId}&typeid=${bloodPressureid}`
        request({
            url:url,
            method:'GET',
            success(res){
                
                let bloodPressure = res.data
                console.log("血压列表：",bloodPressure);
                resolve(bloodPressure)
            },fail(error){
                reject(error)
            }
        })
    })
  },
  //获取用户血糖
  getBloodSuger(){
    return new Promise((resolve,reject)=>{
        let userId = wx.getStorageSync('userid')
        let bloodsugerid = 2  //数据库中血糖id=2
        let url = `healthlog/healthlog/selectByUseridAndTypeid?userid=${userId}&typeid=${bloodsugerid}`
        request({
            url:url,
            method:'GET',
            success(res){
                // console.log("血糖列表：",res.data);
                let bloodsuger = res.data
                resolve(bloodsuger)
            },fail(error){
                reject(error)
            }
        })
    })
  },
  //获取用户体重
  getUserWeight(){
    return new Promise((resolve,reject)=>{
        let userId = wx.getStorageSync('userid')
        let weightid = 1  //数据库中体重id=1 
        let url = `healthlog/healthlog/selectByUseridAndTypeid?userid=${userId}&typeid=${weightid}`
        request({
            url:url,
            method:'GET',
            success(res){
                // console.log("体重列表：",res.data);
                let userweight = res.data
                resolve(userweight)
            },fail(error){
                reject(error)
            }
        })
    })
  },
  setBloodTypeIndex: function() {
    const bloodType = this.data.healthInfo.bloodType;
    const index = this.data.bloodTypes.indexOf(bloodType);
    if (index !== -1) {
      this.setData({
        bloodTypeIndex: index
      });
    }
  },

  setEthnicGroupIndex: function() {
    const ethnicGroup = this.data.userInfo.ethnicGroup;
    const index = this.data.ethnicGroups.indexOf(ethnicGroup);
    if (index !== -1) {
      this.setData({
        ethnicGroupIndex: index
      });
    }
  },

  setEducationLevelIndex: function() {
    const educationLevel = this.data.userInfo.educationLevel;
    const index = this.data.educationLevels.indexOf(educationLevel);
    if (index !== -1) {
      this.setData({
        educationLevelIndex: index
      });
    }
  },

  setMaritalStatusIndex: function() {
    const maritalStatus = this.data.userInfo.maritalStatus;
    const index = this.data.maritalStatuses.indexOf(maritalStatus);
    if (index !== -1) {
      this.setData({
        maritalStatusIndex: index
      });
    }
  },

  goBack: function() {
    wx.navigateBack();
  },

  toggleEdit: function() {
    if (this.data.isEditing) {
      // 保存数据
      this.saveHealthInfo();
    }
    this.setData({
      isEditing: !this.data.isEditing
    });
  },
//页面修改数据时字段对应
  onPhoneInput: function(e) {
    this.setData({
      'userInfo.tel': e.detail.value
    });
  },

  onIdCardInput: function(e) {
    this.setData({
      'userInfo.idcard': e.detail.value
    });
  },

  onCurrentAddressInput: function(e) {
    this.setData({
      'userInfo.address': e.detail.value
    });
  },

//   onRegisteredAddressInput: function(e) {
//     this.setData({
//       'userInfo.registeredAddress': e.detail.value
//     });
//   },

  onRegionChange: function(e) {
    const regionStr = e.detail.value.join(',');
    this.setData({
      'userInfo.region': regionStr
    });
  },

  onNativePlaceInput: function(e) {
    this.setData({
      'userInfo.place': e.detail.value
    });
  },

  onEthnicGroupChange: function(e) {
    const index = e.detail.value;
    this.setData({
      ethnicGroupIndex: index,
      'userInfo.ethnic': this.data.ethnicGroups[index]
    });
  },

  onEducationLevelChange: function(e) {
    console.log("当前学历下标：",e.detail.value);
    const index =Number(e.detail.value) ;
    console.log(index);
    
    // 根据索引来确定对应的数字
    let cultureNumber = 0;
    switch (index) {
        case 0:
            cultureNumber = 1;
            break;
        case 1:
            cultureNumber = 2;
            break;
        case 2:
            cultureNumber = 3;
            break;
        case 3:
            cultureNumber = 4;
            break;
        case 4:
            cultureNumber = 5;
            break;
        default:
            cultureNumber = null;
    }

    this.setData({
        educationLevelIndex: index,
        'userInfo.culture': cultureNumber
    });
    
  },

  onMaritalStatusChange: function(e) {
    const index =Number( e.detail.value );
    const marryid = index+1
    this.setData({
      maritalStatusIndex: index,
      'userInfo.marry': marryid
    });
  },

  onOccupationInput: function(e) {
    this.setData({
      'userInfo.occupation': e.detail.value
    });
  },

  onWorkplaceInput: function(e) {
    this.setData({
      'userInfo.workplace': e.detail.value
    });
  },

  onEmergencyContactInput: function(e) {
    this.setData({
      'userInfo.urgent': e.detail.value
    });
  },

  onEmergencyPhoneInput: function(e) {
    this.setData({
      'userInfo.urgenttel': e.detail.value
    });
  },

  onMedicalInstitutionInput: function(e) {
    this.setData({
      'userInfo.medicalunits': e.detail.value
    });
  },

  onHeightInput: function(e) {
    this.setData({
      'userInfo.height':e.detail.value,
    });
  },

  onWeightInput: function(e) {
    this.setData({
        'userInfo.weight':e.detail.value,
      'healthInfo.weight': e.detail.value
    });
  },

  onBloodPressureInput: function(e) {
    this.setData({
      'healthInfo.bloodPressure': e.detail.value
    });
  },

  onBloodSugarInput: function(e) {
    this.setData({
      'healthInfo.bloodSugar': e.detail.value
    });
  },

  onBloodTypeChange: function(e) {
    const index = e.detail.value;
    this.setData({
      bloodTypeIndex: index,
      'userInfo.blood': this.data.bloodTypes[index],
    });
  },

  onAllergyHistoryChange: function(e) {
    this.setData({
        'userInfo.allergies': e.detail.value,
    });
  },

  onPastMedicalHistoryChange: function(e) {
    this.setData({
      'userInfo.past': e.detail.value
    });
  },

  onFamilyHistoryChange: function(e) {
    this.setData({
      'userInfo.famliypast': e.detail.value
    });
  },

  saveHealthInfo: function() {
     // 确保 userInfo 对象包含所有需要更新的字段
     const userInfoEdit = this.data.userInfo;
    //  console.log("edit",userInfoEdit);
    const healthlogEdit = this.data.healthInfo
    console.log("healthInfo",healthlogEdit);

     // 从本地存储获取 userId，并将其添加到 userInfo 对象中
     let userId = wx.getStorageSync('userid');
     userInfoEdit.userId = userId;
    // 获取当前时间并格式化为包含时分秒的字符串
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    console.log("time",formattedTime);
     // 构建体重、血糖、血压的插入数据
    const weightData = {
        number: healthlogEdit.weight,
        typeid: 1, // 1 表示体重
        time: formattedTime, // 获取当前时间并格式化为 ISO 字符串
        source:1,
        userId: userId
    };

    const bloodSugarData = {
        number: healthlogEdit.bloodSugar,
        typeid: 2, // 2 表示血糖
        time: formattedTime,
        source:1,
        userId: userId
    };

    const bloodPressureData = {
        number: healthlogEdit.bloodPressure,
        typeid: 3, // 3 表示血压
        time: formattedTime,
        source:1,
        userId: userId
    };

     let url = `resident/resident`;
     let healthlogUrl = `healthlog/healthlog`
     request({
         url: url,
         method: 'PUT',
         data: userInfoEdit,
         success(res) {
             console.log("数据保存成功", res.data);
             wx.showToast({
                 title: '保存成功',
                 icon:'success'
             });
             request({
                url: healthlogUrl,
                method: 'POST',
                data: weightData,
                success(weightRes) {
                    console.log("体重数据插入成功", weightRes.data);
                },
                fail(weightError) {
                    console.error("体重数据插入失败", weightError);
                }
            });
            // 成功更新 userInfo 表后，插入体重、血糖、血压数据
            request({
                url: healthlogUrl,
                method: 'POST',
                data: bloodSugarData,
                success(bloodSugarRes) {
                    console.log("血糖数据插入成功", bloodSugarRes.data);
                },
                fail(bloodSugarError) {
                    console.error("血糖数据插入失败", bloodSugarError);
                }
            });

            request({
                url: healthlogUrl,
                method: 'POST',
                data: bloodPressureData,
                success(bloodPressureRes) {
                    console.log("血压数据插入成功", bloodPressureRes.data);
                },
                fail(bloodPressureError) {
                    console.error("血压数据插入失败", bloodPressureError);
                }
            });

         },
         fail(error) {
             console.error("数据保存失败", error);
             wx.showToast({
                 title: '保存失败',
                 icon: 'none'
             });
         }
     });
  }
}); 